<template>
    <div class="batch-search">
        <div class="section-header">
            <h3 class="section-title">
                <el-icon class="title-icon"><Search /></el-icon>
                批量搜索
            </h3>
            <span class="section-desc"
                >通过关键词和筛选条件批量获取抖音数据</span
            >
        </div>

        <div class="search-form">
            <!-- 关键词搜索区域 -->
            <div class="keyword-section">
                <div class="keyword-input">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="请输入搜索关键词，如：美食、旅游、科技等"
                        class="search-input"
                        clearable
                        :disabled="loading || searchProgress.isSearching"
                        @keyup.enter="handleSearch"
                    >
                        <template #prepend>
                            <el-icon><Key /></el-icon>
                        </template>
                    </el-input>
                </div>

                <!-- 热门关键词 -->
                <div class="hot-keywords" v-if="hotKeywords.length > 0">
                    <span class="hot-label">热门：</span>
                    <el-tag
                        v-for="keyword in hotKeywords"
                        :key="keyword"
                        class="hot-tag"
                        size="small"
                        @click="selectKeyword(keyword)"
                    >
                        {{ keyword }}
                    </el-tag>
                </div>
            </div>

            <!-- 筛选参数区域 -->
            <div class="filter-section">
                <el-collapse v-model="activeFilters" class="filter-collapse">
                    <el-collapse-item title="筛选条件" name="filters">
                        <div class="filter-grid">
                            <!-- 内容类型 -->
                            <div class="filter-group" style="margin-top: 10px">
                                <label class="filter-label">内容类型：</label>
                                <el-radio-group
                                    v-model="filters.contentType"
                                    class="filter-radios"
                                >
                                    <el-radio :value="0">综合</el-radio>
                                    <el-radio :value="1">视频</el-radio>
                                    <el-radio :value="2">图文</el-radio>
                                </el-radio-group>
                            </div>

                            <!-- 发布时间 -->
                            <div class="filter-group">
                                <label class="filter-label">发布时间：</label>
                                <el-select
                                    v-model="filters.publishTime"
                                    placeholder="选择时间范围"
                                >
                                    <el-option label="不限" :value="0" />
                                    <el-option label="一天内" :value="1" />
                                    <el-option label="一周内" :value="2" />
                                    <el-option label="半年内" :value="3" />
                                </el-select>
                            </div>

                            <div class="setting-group">
                                <label class="setting-label">排序方式：</label>
                                <el-select
                                    v-model="sortBy"
                                    placeholder="选择排序方式"
                                >
                                    <el-option
                                        label="综合排序"
                                        :value="0"
                                    />
                                    <el-option
                                        label="最多点赞"
                                        :value="1"
                                    />
                                    <el-option
                                        label="最新发布"
                                        :value="2"
                                    />
                                </el-select>
                            </div>

                            <div class="setting-group">
                                <label class="setting-label">搜索数量：</label>
                                <el-select
                                    v-model="searchCount"
                                    placeholder="选择搜索数量"
                                >
                                    <el-option label="10条" value="10" />
                                    <el-option label="20条" value="20" />
                                    <el-option label="50条" value="50" />
                                    <el-option label="100条" value="100" />
                                    <el-option label="200条" value="200" />
                                </el-select>
                            </div>

                            
                        </div>
                    </el-collapse-item>
                </el-collapse>
            </div>

            <!-- 搜索按钮 -->
            <div class="search-actions">
                <el-button
                    type="primary"
                    size="large"
                    :loading="loading || searchProgress.isSearching"
                    @click="handleSearch"
                    :disabled="!searchKeyword.trim()"
                    class="search-btn"
                    :icon="Search"
                >
                    {{ loading ? "搜索中..." : "开始搜索" }}
                </el-button>

                <el-button v-if="loading" @click="stopSearch" class="stop-btn">
                    <el-icon><VideoPause /></el-icon>
                    停止搜索
                </el-button>
            </div>
        </div>

        <!-- 搜索进度 -->
        <div
            class="progress-section"
            v-if="showProgress || searchProgress.isSearching"
        >
            <div class="progress-header">
                <span class="progress-title">搜索进度</span>
                <span class="progress-text">{{ progressText }}</span>
            </div>
            <el-progress
                :percentage="
                    searchProgress.isSearching
                        ? searchProgress.progress
                        : progressPercentage
                "
                :status="progressStatus"
                :stroke-width="8"
            />
            <div class="progress-details">
                <span
                    >已搜索：{{
                        searchProgress.isSearching
                            ? searchProgress.current
                            : searchedCount
                    }}/{{
                        searchProgress.isSearching
                            ? searchProgress.total
                            : searchCount
                    }}</span
                >
                <span>预计剩余：{{ estimatedTime }}</span>
            </div>
        </div>

        <!-- 搜索历史 -->
        <div class="history-section" v-if="searchHistory.length > 0">
            <div class="history-header">
                <span class="history-title">搜索历史</span>
                <el-button text size="small" @click="clearSearchHistory">
                    <el-icon><Delete /></el-icon>
                    清空
                </el-button>
            </div>
            <div class="history-list">
                <div
                    v-for="item in searchHistory.slice(0, 5)"
                    :key="item.id"
                    class="history-item"
                    @click="selectSearchHistory(item)"
                >
                    <div class="history-keyword">{{ item.keyword }}</div>
                    <div class="history-info">
                        <span class="history-count"
                            >{{ item.count }}条结果</span
                        >
                        <span class="history-time">{{ item.time }}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
/** @name 批量搜索组件 */

// 导入Element Plus图标
import {
    Search,
    Key,
    Refresh,
    Check,
    VideoPause,
    Delete,
} from "@element-plus/icons-vue";

// 导入状态管理
import { useMediaStore } from "@/stores/modules/media";
import { storeToRefs } from "pinia";

// 使用媒体store
const mediaStore = useMediaStore();
const { searchHistory, searchProgress } = storeToRefs(mediaStore);
const { addSearchHistory, startSearch, completeSearch } = mediaStore;

// Props
const props = defineProps({
    modelValue: {
        type: String,
        default: "",
    },
});

// Emits
const emit = defineEmits([
    "update:modelValue",
    "search-success",
    "search-error",
]);

// 响应式数据
const searchKeyword = ref("");
const loading = ref(false);
const activeFilters = ref(["filters"]);

// 筛选条件
const filters = ref({
    contentType: 0,
    publishTime: "",
    likesMin: "",
    likesMax: "",
    commentsMin: "",
    commentsMax: "",
    userType: [],
    fansRange: "",
    region: "",
});

// 搜索设置
const searchCount = ref("10");
const sortBy = ref(0);
const includeAnalysis = ref(true);
const autoRefresh = ref(false);

// 进度相关
const showProgress = ref(false);
const progressPercentage = ref(0);
const progressStatus = ref("");
const progressText = ref("");
const searchedCount = ref(0);
const estimatedTime = ref("");

// 热门关键词
const hotKeywords = ref([
    "美食",
    "旅游",
    "科技",
    "时尚",
    "健身",
    "教育",
    "音乐",
    "舞蹈",
    "游戏",
    "宠物",
]);

// 搜索历史已从store中解构，无需重复声明

// 监听props变化
watch(
    () => props.modelValue,
    (newVal) => {
        searchKeyword.value = newVal;
    }
);

// 监听输入变化
watch(searchKeyword, (newVal) => {
    emit("update:modelValue", newVal);
});

/** @name 选择关键词 */
function selectKeyword(keyword) {
    searchKeyword.value = keyword;
}

/** @name 重置筛选条件 */
function resetFilters() {
    filters.value = {
        contentType: ["video", "image"],
        publishTime: "",
        likesMin: "",
        likesMax: "",
        commentsMin: "",
        commentsMax: "",
        userType: [],
        fansRange: "",
        region: "",
    };
    ElMessage.success("筛选条件已重置");
}

/** @name 应用筛选条件 */
function applyFilters() {
    ElMessage.success("筛选条件已应用");
}

/** @name 处理搜索 */
async function handleSearch() {
    if (!searchKeyword.value.trim()) {
        ElMessage.warning("请输入搜索关键词");
        return;
    }

    // 使用store管理搜索状态
    mediaStore.startSearch(parseInt(searchCount.value));

    loading.value = true;
    showProgress.value = true;
    progressPercentage.value = 0;
    progressStatus.value = "";
    searchedCount.value = 0;

    try {
        // 添加到搜索历史
        addToSearchHistory();

        // 模拟搜索过程
        await simulateSearch();

        // 搜索成功
        const result = {
            keyword: searchKeyword.value,
            count: parseInt(searchCount.value),
            filters: { ...filters.value },
            data: generateSearchResults(),
        };

        progressStatus.value = "success";
        progressText.value = "搜索完成";

        // 使用store完成搜索
        mediaStore.completeSearch();

        ElMessage.success(`搜索完成，共找到 ${result.count} 条结果`);
        emit("search-success", result);
    } catch (error) {
        progressStatus.value = "exception";
        progressText.value = "搜索失败";
        ElMessage.error("搜索失败，请重试");
        emit("search-error", error);
    } finally {
        loading.value = false;
    }
}

/** @name 停止搜索 */
function stopSearch() {
    loading.value = false;
    showProgress.value = false;
    ElMessage.info("搜索已停止");
}

/** @name 模拟搜索过程 */
async function simulateSearch() {
    const totalCount = parseInt(searchCount.value);
    const steps = Math.ceil(totalCount / 10);

    for (let i = 0; i < steps; i++) {
        const currentCount = Math.min((i + 1) * 10, totalCount);
        searchedCount.value = currentCount;
        progressPercentage.value = Math.floor(
            (currentCount / totalCount) * 100
        );
        progressText.value = `正在搜索第 ${currentCount} 条数据...`;

        const remainingSteps = steps - i - 1;
        estimatedTime.value =
            remainingSteps > 0 ? `${remainingSteps * 2}秒` : "即将完成";

        await new Promise((resolve) => setTimeout(resolve, 800));
    }
}

/** @name 生成搜索结果 */
function generateSearchResults() {
    const count = parseInt(searchCount.value);
    const results = [];

    for (let i = 0; i < count; i++) {
        results.push({
            id: Date.now() + i,
            title: `${searchKeyword.value}相关作品 ${i + 1}`,
            cover: `https://picsum.photos/300/400?random=${Date.now() + i}`,
            type:
                filters.value.contentType.includes("video") &&
                Math.random() > 0.3
                    ? "video"
                    : "image",
            authorName: `用户${Math.floor(Math.random() * 1000) + 1}`,
            authorAvatar: `https://picsum.photos/50/50?random=${
                Date.now() + i + 2000
            }`,
            likes: Math.floor(Math.random() * 500000) + 1000,
            comments: Math.floor(Math.random() * 20000) + 100,
            shares: Math.floor(Math.random() * 5000) + 50,
            publishTime: new Date(
                Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000
            ).toLocaleDateString(),
            tags: generateRandomTags(),
        });
    }

    return results;
}

/** @name 生成随机标签 */
function generateRandomTags() {
    const allTags = [
        "热门",
        "推荐",
        "原创",
        "精选",
        "新人",
        "达人",
        "官方",
        "认证",
    ];
    const tagCount = Math.floor(Math.random() * 3) + 1;
    const selectedTags = [];

    for (let i = 0; i < tagCount; i++) {
        const randomTag = allTags[Math.floor(Math.random() * allTags.length)];
        if (!selectedTags.includes(randomTag)) {
            selectedTags.push(randomTag);
        }
    }

    return selectedTags;
}

/** @name 添加到搜索历史 */
function addToSearchHistory() {
    const historyItem = {
        id: Date.now(),
        keyword: searchKeyword.value,
        count: parseInt(searchCount.value),
        filters: { ...filters.value },
        time: new Date().toLocaleString(),
    };

    // 移除重复的关键词
    searchHistory.value = searchHistory.value.filter(
        (item) => item.keyword !== searchKeyword.value
    );
    searchHistory.value.unshift(historyItem);

    // 保持最多20条记录
    if (searchHistory.value.length > 20) {
        searchHistory.value = searchHistory.value.slice(0, 20);
    }

    // 保存到本地存储
    localStorage.setItem("search-history", JSON.stringify(searchHistory.value));
}

/** @name 选择搜索历史 */
function selectSearchHistory(item) {
    searchKeyword.value = item.keyword;
    searchCount.value = item.count.toString();
    filters.value = { ...item.filters };
}

/** @name 清空搜索历史 */
function clearSearchHistory() {
    ElMessageBox.confirm("确定要清空所有搜索历史吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        searchHistory.value = [];
        localStorage.removeItem("search-history");
        ElMessage.success("搜索历史已清空");
    });
}

// 组件挂载时加载搜索历史
onMounted(() => {
    const saved = localStorage.getItem("search-history");
    if (saved) {
        try {
            searchHistory.value = JSON.parse(saved);
        } catch (error) {
            console.error("加载搜索历史失败:", error);
        }
    }
});
</script>

<style lang="scss" scoped>
.batch-search {
    background: $qf-color-bg2;
    border: 1px solid $qf-border-color;
    border-radius: $qf-border-radius-lg;
    padding: 20px;

    .section-header {
        margin-bottom: 20px;

        .section-title {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 18px;
            font-weight: 600;
            color: $qf-text-color-primary;
            margin: 0 0 4px 0;

            .title-icon {
                color: $qf-primary;
            }
        }

        .section-desc {
            font-size: 14px;
            color: $qf-text-color-secondary;
        }
    }

    .search-form {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .keyword-section {
            .keyword-input {
                margin-bottom: 12px;

                .search-input {
                    :deep(.el-input-group__prepend) {
                        background: $qf-color-bg3;
                        border-color: $qf-border-color;
                        color: $qf-text-color-secondary;
                    }
                }
            }

            .hot-keywords {
                display: flex;
                align-items: center;
                gap: 8px;
                flex-wrap: wrap;

                .hot-label {
                    font-size: 13px;
                    color: $qf-text-color-secondary;
                    flex-shrink: 0;
                }

                .hot-tag {
                    cursor: pointer;
                    transition: all 0.2s ease;

                    &:hover {
                        background: $qf-primary;
                        color: white;
                    }
                }
            }
        }

        .filter-section {
            .filter-collapse {
                :deep(.el-collapse-item__header) {
                    background: $qf-color-bg3;
                    border-color: $qf-border-color;
                    color: $qf-text-color-primary;
                }

                :deep(.el-collapse-item__content) {
                    background: $qf-color-bg3;
                    border-color: $qf-border-color;
                }
            }

            .filter-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
                gap: 16px;
                margin-bottom: 16px;

                .filter-group {
                    display: flex;
                    align-items: center;
                    gap: 12px;

                    .filter-label {
                        font-size: 14px;
                        color: $qf-text-color-secondary;
                        min-width: 70px;
                        flex-shrink: 0;
                    }

                    .filter-checkboxes {
                        display: flex;
                        gap: 12px;
                        flex-wrap: wrap;
                    }

                    .range-inputs {
                        display: flex;
                        align-items: center;
                        gap: 8px;

                        .el-input {
                            width: 80px;
                        }

                        .range-separator {
                            color: $qf-text-color-secondary;
                            font-size: 14px;
                        }
                    }

                    .el-select {
                        min-width: 120px;
                    }
                }
            }

            .filter-actions {
                display: flex;
                gap: 12px;
                justify-content: flex-end;
                padding-top: 12px;
                border-top: 1px solid $qf-border-color;
            }
        }

        .search-settings {
            display: flex;
            align-items: center;
            gap: 24px;
            padding: 16px;
            background: $qf-color-bg3;
            border: 1px solid $qf-border-color;
            border-radius: $qf-border-radius-base;
            flex-wrap: wrap;
        }

        .search-actions {
            display: flex;
            gap: 12px;
            justify-content: center;

            .search-btn {
                min-width: 120px;
            }

            .stop-btn {
                color: $qf-danger-color;
                border-color: $qf-danger-color;

                &:hover {
                    background: $qf-danger-color;
                    color: white;
                }
            }
        }
    }

    .progress-section {
        margin-top: 16px;
        padding: 16px;
        background: $qf-color-bg3;
        border: 1px solid $qf-border-color;
        border-radius: $qf-border-radius-base;

        .progress-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;

            .progress-title {
                font-size: 14px;
                font-weight: 500;
                color: $qf-text-color-primary;
            }

            .progress-text {
                font-size: 13px;
                color: $qf-text-color-secondary;
            }
        }

        .progress-details {
            display: flex;
            justify-content: space-between;
            margin-top: 8px;
            font-size: 12px;
            color: $qf-text-color-disabled;
        }
    }

    .history-section {
        margin-top: 16px;

        .history-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 8px;

            .history-title {
                font-size: 14px;
                font-weight: 500;
                color: $qf-text-color-primary;
            }
        }

        .history-list {
            display: flex;
            flex-direction: column;
            gap: 4px;

            .history-item {
                padding: 8px 12px;
                background: $qf-color-bg3;
                border: 1px solid $qf-border-color;
                border-radius: $qf-border-radius-base;
                cursor: pointer;
                transition: all 0.2s ease;

                &:hover {
                    border-color: $qf-primary;
                    background: $qf-color-bg4;
                }

                .history-keyword {
                    font-size: 14px;
                    color: $qf-text-color-primary;
                    margin-bottom: 4px;
                    font-weight: 500;
                }

                .history-info {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .history-count {
                        font-size: 12px;
                        color: $qf-primary;
                        background: rgba(151, 164, 255, 0.1);
                        padding: 2px 6px;
                        border-radius: $qf-border-radius-sm;
                    }

                    .history-time {
                        font-size: 12px;
                        color: $qf-text-color-disabled;
                    }
                }
            }
        }
    }
}
.setting-group {
    display: flex;
    align-items: center;
    gap: 8px;

    .setting-label {
        font-size: 14px;
        color: $qf-text-color-secondary;
        flex-shrink: 0;
    }

    

    .el-checkbox {
        margin: 0;
    }
}
</style>
